package jmine.selenium.services.validar;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;

import jmine.selenium.services.AbstractSeleniumService;
import jmine.tec.services.annotations.Execution;
import jmine.tec.services.annotations.ServiceImplementor;
import jmine.tec.services.api.ActionsEnum;

import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;
import org.junit.Assert;

/**
 * Serviço que percorre por todas as paginas acessiveis pelo principal.
 * 
 * @author Rafael Volpato
 * @date Apr 10, 2012
 */
@ServiceImplementor(action = ActionsEnum.VALIDAR)
public class JSCookMenuService extends AbstractSeleniumService {

    private static final Logger LOG = Logger.getLogger(JSCookMenuService.class);

    /**
     * Percorre todos os itens do menu, validando que a página é aberta com sucesso.
     */
    @Execution
    public void execute() {
        List<String> errors = new ArrayList<String>();
        Map<String, List<String>> menu = JSCookMenuHelper.getMenu(this.getSelenium());

        for (Entry<String, List<String>> menuEntry : menu.entrySet()) {
            List<String> path = menuEntry.getValue();

            try {
                JSCookMenuHelper.goTo(this.getSelenium(), path.toArray(new String[path.size()]));

                String expectedBreadCrumb = StringUtils.join(path, " - ");
                String breadCrumb = this.getSelenium().getText("//div[@class=\"breadcrumb\"]/span");
                if ("".equals(breadCrumb)) {
                    // Hack para suportar o breadcrumb em JSF
                    breadCrumb = this.getSelenium().getAttribute("BreadCrumb@value");
                    expectedBreadCrumb = StringUtils.join(path, ":");
                }
                Assert.assertEquals("BreadCrumb", expectedBreadCrumb.trim(), breadCrumb.trim());
            } catch (Throwable t) {
                errors.add(StringUtils.join(path, "-") + " :" + t.getMessage() + "\n");
            }
        }

        if (!errors.isEmpty()) {
            StringBuilder sb = new StringBuilder();
            for (String error : errors) {
                sb.append(error);
                LOG.fatal(error);
            }
            fail("Não foi possivel validar todos os itens do menu com sucesso!\n" + sb.toString() + "\n");
        }
    }
}
